(function(w){


	var lsa = {
		set:function(key,value){
			return localStorage.setItem(key, value);
		},
		get:function(key){
			return localStorage.getItem(key);
		},
		remove:function(key){
			return localStorage.removeItem(key);
		}
	}


	var wxCloud={

		cloud:function(){

			// 不同于登录模式，在未登录模式中，资源方小程序对应环境下的 cloudbase_auth 不会被调用，但此处 init 也是必须的。
			const a = new cloud.Cloud({
			  identityless: true,
			  resourceAppid: 'wx6c4635b65eaec6dd',
			  resourceEnv: 'srrz-2g24l1oea7a7e67e',
			})
			
			a.init()

			return a

		},
		callContainer:function(){

			const a = this.cloud()
			//云托管调用
			a.callContainer({
				path:'/container-top237',
				method:'GET',
				success:function(data){
					console.log(data.data)
				}
			})

		},
		db:function(){var db = this.cloud().database({env:'srrz-2g24l1oea7a7e67e'});return db},
		uploadFile:function(){

			const a = this.cloud()

			//文件上传 需要将脚本文件上传至静态网页
			a.uploadFile({
			  cloudPath: 'top237-001.zip',
			  file: 'D:/phpstudy_pro/WWW/微信Web生态/top237-001.zip',
			  success: res => {
			    // get resource ID
			    console.log(res.fileID)
			  },
			  fail: err => {
			    // handle error
			    console.log(err)
			  }
			})
		},
		getNavMulvList:function(fun){
			var self =  this;
			this.db().collection('shijidb').where({}).orderBy('index','asc').get({

				success: function(res) {
			    	fun(res.data)

			  	},
			  	fail:function(err){
			  		fun(err)
			  	}
			})
		},
		addZanMeiFangWen:function(data,fun){

			this.cloud().callFunction({
				name:'addZanmeiFangWen',
				data:data,
				success:function(res){
					fun(res)
				}
			})
		},
		getzanmeiitem:function(fun){

			this.cloud().callFunction({
				name:'getzanmeiitem',
				data:{},
				success:function(res){

					fun(res.result.data)
					
				},
				fail:function(erro){
					console.log(erro)
				}
			})
		}


	}


	var domain={
		init:function(){

			this.nav()
			this.listActive()
			this.editionUpdate()
		},
		//nav导航html渲染
		nav:function(){


			if(lsa.get('navMuluList')==undefined || lsa.get('zmitem')==undefined ){

				this.refreshNavAndList()

				return

			}

			var navlist = JSON.parse(localStorage.getItem("navMuluList"))

			var zm = JSON.parse(lsa.get("zmitem"))

			var listzmText = doT.template($("#listzmtmpl").text());

			// var navListText = doT.template($("#navlisttmpl").text());

			// $("#navbar").html(navListText(navlist));

			$("#list").html(listzmText(zm));

		},
		//更新渲染list页面
		zmitem:function(){

			var listzmText = doT.template($("#listzmtmpl").text());

			var zm = JSON.parse(lsa.get("zmitem"))


			if(arguments.length>0){

				if(arguments[0]==undefined){
					$("#list").html(listzmText(zm));
					return
				}

				if(arguments[0]==" "){
					$("#list").html(listzmText(zm));
					return
				}

				if(arguments[0]==""){
					$("#list").html(listzmText(zm));
					return
				}


				nzm = []

				var seacherStr = arguments[0]

				zm.forEach(function(item){

					var shijiname = item['xuhao'] + item['mulu']

					if(shijiname.indexOf(seacherStr)!==-1){
						nzm.push(item)

					}
			
				})


				$("#list").html(listzmText(nzm));

				

				return


			}

			$("#list").html(listzmText(zm));
	

		},
		//列表点击激活
		listActive:function(){

			var self  = this

			$('#list').on('click','.list-group-item', function(e){

				if($(e.currentTarget).attr('class')!=='list-group-item active'){

					$(".list-group-item").each(function(){
						$(this).removeClass('liActive')
					})

					$(e.currentTarget).addClass('liActive')

					var filename = $(e.currentTarget).find('a').html().replace(/\d+\./,'')

					var zmitems = JSON.parse(lsa.get('zmitem'))

					var isAudio = false

					var id=''

					zmitems.forEach(function(item){
						
						if(item['mulu']==filename){

							console.log(filename)

							id  = item['_id']
						}

					})

					$(e.currentTarget).find('span').each(function(){

						if($(this).attr('class')==="glyphicon glyphicon-music"){

							isAudio=true

						}
					})

					self.tonav(id)

				}

			})
		},
		//跳转到新页面
		tonav:function(id){

			var url = "play.html?d=" + id;

			window.location.href =url


		},
		//获取传递参数
		getcanshu:function(){

			var canshu = window.location.search.replace("?","")

			var arr = canshu.split("&")

			var canshuobj = {}

			for(var i =  0  ; i < arr.length ; i++){

				var c = arr[i].split("=")

				canshuobj[c[0]] = c[1]

			}

			return canshuobj
		},
		//版本更新和硬刷新列表模块及公告模块
		editionUpdate:function(){

			var self =  this
			// 调用数据 库版本控制器
			wxCloud.cloud().callFunction(

				{
					name:'gitSgbVersion',
					data:{
						dbname:'sgb-version-control'
					},
					success:function(res){
						
						var edition = res.result.data[0]['versoion']

						// console.log('版本控制调用成功=>',res)

						if(lsa.get('edition')==undefined || lsa.get('edition')!==edition){

							lsa.set('edition',edition)

							self.refreshNavAndList()

							self.openPublicAnnouncement(res.result.data[0]['context'])
						
						}

					},
					fail:function(erro){

						console.log(erro)
					}
				}
			)



			

		},
		//更新列表和导航功能
		refreshNavAndList:function(){

			var self = this;

			var index = layer.load(1, {
			  shade: [0.1,'#fff'] //0.1透明度的白色背景
			});

			wxCloud.getNavMulvList(function(data){

				lsa.set('navMuluList',JSON.stringify(data))

				var navlist = data

				wxCloud.getzanmeiitem(function(data1){

					lsa.set('zmitem',JSON.stringify(data1))

					var zm = data1

					var listzmText = doT.template($("#listzmtmpl").text());

					var navListText = doT.template($("#navlisttmpl").text());

					$("#navbar").html(navListText(navlist));

					$("#list").html(listzmText(zm));

					layer.close(index)

				})

			})
	
		},
		openPublicAnnouncement:function(src){

			layer.open({
				  type: 1,
				  content: src, //这里content是一个普通的String
				  shadeClose:true,
				  title:'版本更新通知',
				  anim:0,
				  area:['80%','70%'],
				  
				});
		},

	}

	//导航js动态元素封装
	var nav = {


		scrollevent:function(box,list,nav){ //移动监听nav

			//监听的盒子元素  参数1
			//要监听的滚动列表元素 参数2
			//导航的元素 参数3

			$(box).scroll(function(e){

				var maodianEle = $( list + '>.active')

				if(maodianEle.length == 0){
					return
				}

				var scrollTop = e.currentTarget.scrollTop + 1

				var offsetVal = $(maodianEle[0])[0].offsetTop //顶部偏移距离

				for(var i = 0 ; i < maodianEle.length ; i++){

					if(scrollTop > $(maodianEle[i])[0].offsetTop-offsetVal){

						$(nav).find("li").each(function () {

						　　　　$(this).removeClass("active");

					　　　　});

						$($(nav).find("li")[i]).addClass("active")

					}


				}

			})

		}

	}

	//input框js

	var seacherInput = {

		init:function(){

			this.seacherInput()
			this.removeSeacher()
		},
		seacherInput:function(){

			$("#seacherInput").bind("input propertychange",function(e){

			domain.zmitem($(this).val())

			if($(this).val().length>0){

				$(".removeSeacher").show()
			}else{
				$(".removeSeacher").hide()
			}

			})



		},
		removeSeacher:function(){

			$(".removeSeacher").click(function(){

				$("#seacherInput").val('')
				domain.zmitem()
				$(this).hide()
			})

		}
	}

	window.wxCloud = wxCloud
	window.lsa = lsa
	window.domain = domain
	window.nav = nav
	window.seacherInput = seacherInput

})(window)


